package com.gyh.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gyh.entity.User;
import com.gyh.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired UserService userService;
	
	@ResponseBody
	@RequestMapping("/list")
	public Map<String,Object> userInfo() {
		Map<String,Object> result = new HashMap<String,Object>();
		List<User> user = userService.UserInfo();
		Set<String> roles = userService.sreachRoles("admin");
		Set<String> permission = userService.searchPermissions("admin");
		result.put("set", roles);
		result.put("user", user);
		result.put("permission", permission);
		
		return result;
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public void loginInfo(HttpServletRequest request,HttpServletResponse response,String userName,String password) throws ServletException, IOException {
		logger.info(userName+"用户，正在登入操作。。。。。。。。。");
		Map<String,Object> result = new HashMap<String,Object>();
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		try {
			subject.login(token);
			Session session = subject.getSession();
			result.put("message", "登入成功");
			session.setAttribute("userName", userName);
			response.sendRedirect("/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("登入失败！！！！！！！！");
			request.setAttribute("errorInfo", "用户名或者密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}
	
	
	
	
}
